package com.moyoutian.leetcode;

/**
 * 23. 合并K个升序链表
 * <p>
 * 给你一个链表数组，每个链表都已经按升序排列。
 * <p>
 * 请你将所有链表合并到一个升序链表中，返回合并后的链表。
 * <p>
 * 示例 1：
 * <p>
 * 输入：lists = [[1,4,5],[1,3,4],[2,6]]
 * 输出：[1,1,2,3,4,4,5,6]
 * 解释：链表数组如下：
 * [
 * 1->4->5,
 * 1->3->4,
 * 2->6
 * ]
 * 将它们合并到一个有序链表中得到。
 * 1->1->2->3->4->4->5->6
 * 示例 2：
 * <p>
 * 输入：lists = []
 * 输出：[]
 * 示例 3：
 * <p>
 * 输入：lists = [[]]
 * 输出：[]
 * <p>
 * <p>
 * 提示：
 * <p>
 * k == lists.length
 * 0 <= k <= 10^4
 * 0 <= lists[i].length <= 500
 * -10^4 <= lists[i][j] <= 10^4
 * lists[i] 按 升序 排列
 * lists[i].length 的总和不超过 10^4
 */
public class Demo23 {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode l11 = new ListNode(2);
        ListNode l12 = new ListNode(3);
        l1.next = l11;
        l11.next = l12;

        ListNode l2 = new ListNode(2);
        ListNode l21 = new ListNode(3);
        ListNode l22 = new ListNode(4);
        l2.next = l21;
        l21.next = l22;
        ListNode[] lists = new ListNode[]{l1, l2};

        ListNode listNode = mergeKLists(lists);
        System.out.println("Demo23.main");
    }

    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }
        if (lists.length == 1) {
            return lists[0];
        }
        ListNode header = lists[0];
        for (int i = 1; i < lists.length; i++) {
            header = mergeTwoLists(header, lists[i]);
        }
        return header;
    }

    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        } else if (l2 == null) {
            return l1;
        }
        ListNode tempL = l1;
        ListNode tempR = l2;
        ListNode header;
        ListNode temp;
        if (tempL.val < tempR.val) {
            header = tempL;
            temp = tempL;
            tempL = tempL.next;
        } else {
            header = tempR;
            temp = tempR;
            tempR = tempR.next;
        }


        while (tempL != null && tempR != null) {
            if (tempL.val < tempR.val) {
                temp.next = tempL;
                tempL = tempL.next;
            } else {
                temp.next = tempR;
                tempR = tempR.next;
            }
            temp = temp.next;
        }
        if (tempL != null) {
            temp.next = tempL;
        } else {
            temp.next = tempR;
        }
        return header;
    }
}
